package com.wandian.texas.command.texas;

import java.sql.Timestamp;

import com.wandian.texas.BaseCommandObject;
import com.wandian.texas.GameData;
import com.wandian.texas.GamePool;
import com.wandian.texas.GameServer;
import com.wandian.texas.UserMgr;
import com.wandian.command.Cmd;
import com.wandian.command.UserCommand;
import com.wandian.texas.dao.Impl.GameRoomDaoImpl;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.DaoManager;
import com.wandian.texas.entity.UserInfoEntity;
import com.wandian.texas.protocol.Protocol;
import com.wandian.util.Log;

@Cmd(code = Protocol.UserLoginCmd, desc = "")
public class UserLoginCmd extends UserCommand {

	public UserLoginCmd() {
		this.setCommandName("UserLoginCmd");
	}

	@Override
	public void execute(BaseCommandObject cmdObject) {
		super.execute(cmdObject);
		// 0success,1,2,3
		// Log.info(String.format("[%s]user login %s", this.getCommandName(),
		// cmdObject.byteToHex()));
		byte type = cmdObject.readByte();
		UserInfoEntity user = new UserInfoEntity();
		user.userName = cmdObject.readString();
		user.password = cmdObject.readString();
//		user.serverId = GameData.SERVER.ServerId;
		if (type != 125) {
			user.key = cmdObject.readInt();
		}
		GameRoomDaoImpl gameDao = GamePool.gameRoomDao(cmdObject.dbIndex);
		int result = 1;
		if (gameDao.loginCheckAccount(user)) {
			// 如果登陆账号验证成功，继续验证10分钟有效期GameServerCheckAllow
			/*0 成功			   1 不允许登录，非法登录			   2 登录超时			   3 已在游戏中				   4 check不对*/
			if (type != 125) {
				// 独立的客户端登陆
				if (!GameData.checkLoginOnly) {
					// 如果此人记录没有，则增加一条
					if (gameDao.execQueryCount("select  Account From OnlyLogin where Account=? and ServerIdx=? and GameId=?", DBMgr.AccountDB, user.userName, GameData.SERVER.ServerIndex, GameData.SERVER.GameId) < 1) {
						if (gameDao.execSql("insert into OnlyLogin(Account,Flag,ServerIdx,GameId,checkkey,TableId,GameByte)VALUES(?,?,?,?,?,?,?)", DBMgr.AccountDB, user.userName, 1, GameData.SERVER.ServerIndex, GameData.SERVER.GameId, user.key, 0, 0) != 1) {
							// 程序插入失败
							result = 12;
						}
					}
//					gameDao.execSql("delete from OnlyLogin where ServerIdx =? and Account=?", DBMgr.AccountDB, GameData.SERVER.ServerIndex, user.userName);
				}
				result = gameDao.checkOnlyLogin(user);
			} else {
				// 机器人不需要2步check
				result = 0;
				// user.nickName = user.userName;
				// user.money = 100000;
			}
			if (result == 0) {
				// 如果本地数据库不存在用户
				if (!DaoManager.UserInfoDao(cmdObject.dbIndex).getUserInfo(user)) {
					// 这里验证失败，说明玩家在额外配置表没有记录，应该是第一次进游戏，生成额外信息，同时保存AccountId
					user.icon = user.sex == 0 ? "1" : "5";
					user.nickName = user.userName;// 第一次客户端玩家改昵称
					DaoManager.GameRoomDao(cmdObject.dbIndex).addUserFirstLogin(user);
					if (user.userId < 1) {
						result = 12;
						Log.error("import user error");
						// throw new
						// IllegalArgumentException("import user error");
					}

				} else {
					// 如果上次服务器宕机，玩家坐着stake，没有被加入money中去
					if (user.stake + user.gameBet > 0) {
						float addMoney = (user.stake + user.gameBet) / GameData.StakeToMoney;
						// 调用存储过程 [AddPlayerMoney]
						if (gameDao.executeNoQuery("AddPlayerMoney", DBMgr.AccountDB, user.AccountId, addMoney) != -11) {
							// 影响行为1，才成功~失败~
							user.stake = 0;
							// 清除gamebet，增加负的bet
							if (user.gameBet > 0) {
								if (gameDao.executeNoQuery("sp_AddPlayMoneyLogWhenError", DBMgr.TexasPokerDB, user.userId, user.AccountId, -user.gameBet, 0) != -1) {
									user.gameBet = 0;
								} else {
									result = 12;
								}
							}
							// stake gamebat set 0
							if (!DaoManager.UserInfoDao(cmdObject.dbIndex).exeSql("  UPDATE PlayerInfo SET  Stake=?,GameBet=? Where UserId=? ;", DBMgr.TexasPokerDB, 0, 0, user.userId)) {
								Log.error("[UserLoginCmd]玩家登陆,保存状态失败!UPDATE PlayerInfo SET  Stake=?,GameBet=? error");
								result = 12;
							}
						} else {
							result = 12;
						}
					}
				}

			}
			if (result == 0) {
				// flag=2 PlayInGame ,@TableID smallint, @GameByte tinyint
				//
				if (gameDao.executeProcedureReturn("PlayInGame", DBMgr.AccountDB, user.userName, user.key, GameData.SERVER.ServerIndex, GameData.SERVER.GameId, 0, 0) != 1) {
					// 程序update失败
					result = 12;
				}

				// 取玩家money
				user.money = gameDao.getUserMoney(user.AccountId);
				// 将实际钱转换成游戏内的钱，增减实际前,需要筹码换成钱，如user.money/MoneyToStake
				// user.money = user.money * GameData.StakeToMoney;
			}
		}
		if (user.stake > 0) {
			throw new IllegalArgumentException("login,and stake >0 error " + user);
		}
		cmdObject.writeBegin();
		if (result == 0) {
			cmdObject.setStatus(GameData.CHECKUSERSUCC);
			cmdObject.setUser(user);
			user.setCheckLogin(true);
			// UserMgr.I().onlineUserMap.put(userName, cmdObject.sessionObject);
			// UserMgr.I().onlineUserList.add(cmdObject.sessionObject);
			UserMgr.I().loginOn(cmdObject.sessionObject);
			cmdObject.writeByte((byte) 0);// 成功标志
			cmdObject.writeInt(user.getUserId());
			cmdObject.writeString(user.getUserName());
			cmdObject.writeString(user.getNickName());
			cmdObject.writeBytes(user.getHeadImage());
			cmdObject.writeByte(user.getSex());
			// cmdObject.writeString(user.getEmail());
			// cmdObject.writeString(user.getMobile());
			// cmdObject.writeInt(user.getScore());
			cmdObject.writeFloat(user.getMoney());
			// cmdObject.writeInt(user.getGold());

		} else {
			cmdObject.setStatus(GameData.WAITINGCHECKSUCC);
			cmdObject.setCmdStatus(1, (byte) 0);// 继续check login
			cmdObject.writeByte((byte) result);// 成功标志
		}
		cmdObject.writeEnd();
		UserMgr.I().SendData(cmdObject.sessionObject, cmdObject);

		// 保存登陆信息
		if (result == 0) {
//			Log.info(user.getNickName() + "登陆成功");
			if (!DaoManager.UserInfoDao(cmdObject.dbIndex).exeSql("  UPDATE PlayerInfo SET  ServerId=?,CurrentState=?,LastLoginTime=?,LastLoginIp=?,CurrentServerId=?,Money=?,Stake=? Where UserId=? ;", DBMgr.TexasPokerDB, GameData.SERVER.ServerId, 1, new Timestamp(System.currentTimeMillis()), cmdObject.sessionObject.ipAddress, GameData.SERVER.ServerId, user.money, 0, user.userId)) {
				Log.error("[UserLoginCmd]玩家登陆,保存状态失败!");
			}
			// 登陆成功，将当前缓存的最新积宝发送过去
			cmdObject.setCmd(Protocol.CMD_UPDATE_CORNUCOPIA);
			cmdObject.writeBegin();
			cmdObject.writeFloat(GameServer.requestor.toCornucopia);// 数据库返回最终数,让客户端在指定时间滚动
			cmdObject.writeFloat(GameServer.requestor.offsetCornucopia);
			cmdObject.writeInt(GameServer.requestor.updateCornucopiaSecond);// 告诉客户端时间
			cmdObject.writeEnd();
			UserMgr.I().SendData(cmdObject);
		} else {
			Log.debug("登陆失败");
		}
		// SessionMgrImp.getInstance().SendData(
		// cmdObject.sessionObject, cmdObject.getBytes(), cmdObject.getCmd());
		// 广播消息
		/*
		 * if (result == 0) { cmdObject.writeBegin();
		 * cmdObject.writeString("系统:"); cmdObject.writeByte((byte) 0);
		 * cmdObject.writeString(String.format("欢迎玩家[%s]来到玩点聊天室",
		 * user.getRealName())); cmdObject.writeEnd();
		 * UserMgr.I().broadCastToAllOnlines((short) 8000,
		 * cmdObject.getBytes()); }
		 */
	}
}
